package com.xkstream.client.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xkstream.client.R;
import com.xkstream.client.application.Application;
import com.xkstream.client.base.BaseActivity;
import com.xkstream.client.base.WatcherAdapter;
import com.xkstream.client.entity.User;
import com.xkstream.client.presenter.UserContract;
import com.xkstream.client.presenter.UserPresenter;
import com.xkstream.client.ui.live.StartLiveActivity;
import com.xkstream.client.utils.DeviceUtils;
import com.xkstream.client.utils.MD5Util;
import com.xkstream.client.utils.PreferenceUtils;
import com.xkstream.client.view.ResizeLayout;

import org.reactivestreams.Subscriber;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindColor;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;

/**
 * Created by xiaoyi on 2017-9-23.
 */

public class LoginActivity_V2 extends BaseActivity<UserContract.Presenter> implements UserContract.View {
    @BindView(R.id.edt_account)
    EditText edtAccount;
    @BindView(R.id.edt_pwd)
    EditText edtPwd;
    @BindView(R.id.tv_remember_pwd)
    TextView tvRememberPwd;
    @BindView(R.id.tv_forget_pwd)
    TextView tvForgetPwd;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.tvVersion)
    TextView tvVersion;

    @BindColor(R.color.login_input_selected)
    int colorInputSelected;
    @BindColor(R.color.login_input_unselected)
    int colorInputUnselected;

    boolean rememberPwd = true;

    private final String USERNAME = "username";

    private final String PASSWORD = "password";

    private String userName;
    private String password;

    @BindView(R.id.root)
    ResizeLayout root;

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login_v2);
        ButterKnife.bind(this);
        presenter = new UserPresenter(this);
        initListener();
        setUserNameAndPasswordPreference();
        root.setOnKeyboardShowListener(new ResizeLayout.OnkeyboardShowListener() {
            @Override
            public void onKeyboardShow(int height) {
                int[] location = new int[2];
                tvRegister.getLocationOnScreen(location);
                int position = DeviceUtils.deviceHeight(LoginActivity_V2.this) - location[1] - tvRegister.getHeight();
                root.setPadding(0, -(height - position), 0, 0);

            }

            @Override
            public void onKeyboardHide() {
                root.setPadding(0, 0, 0, 0);
            }
        });
        tvVersion.setText("Version:" + DeviceUtils.getVersionName(this));
    }

    private void initListener() {
        edtAccount.setOnFocusChangeListener((v, focus) -> {
            edtAccount.setCompoundDrawablesWithIntrinsicBounds(
                    focus ? R.drawable.nick_selected : R.drawable.nick_unselected,
                    0, 0, 0);
            edtAccount.setBackgroundResource(focus ? R.drawable.login_input_selected
                    : R.drawable.login_input_unselected);
            edtAccount.setTextColor(focus ? colorInputSelected : colorInputUnselected);
            edtAccount.setHintTextColor(focus ? colorInputSelected : colorInputUnselected);


        });

        edtPwd.setOnFocusChangeListener((v, focus) -> {
            edtPwd.setCompoundDrawablesWithIntrinsicBounds(
                    focus ? R.drawable.pwd_selected : R.drawable.pwd_unselected,
                    0, 0, 0);
            edtPwd.setBackgroundResource(focus ? R.drawable.login_input_selected
                    : R.drawable.login_input_unselected);
            edtPwd.setTextColor(focus ? colorInputSelected : colorInputUnselected);
            edtPwd.setHintTextColor(focus ? colorInputSelected : colorInputUnselected);
            showSoftKeyboad();
        });

        edtAccount.addTextChangedListener(new WatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                setBtnState();
            }
        });

        edtPwd.addTextChangedListener(new WatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                setBtnState();
            }
        });

    }


    private void setBtnState() {
        if (edtAccount.getText().length() >= 4 && edtPwd.getText().length() >= 4) {
            tvLogin.setBackgroundResource(R.drawable.btn_clickable);
        } else {
            tvLogin.setBackgroundResource(R.drawable.btn_unclickable);
        }
    }


    /**
     * 设置输入框默认账号密码
     */
    private void setUserNameAndPasswordPreference() {
        String userName = PreferenceUtils.getString(USERNAME);
        String password = PreferenceUtils.getString(PASSWORD);
        if (!TextUtils.isEmpty(userName)) {
            edtAccount.setText(userName);
            edtAccount.setSelection(userName.length());
        }
        if (!TextUtils.isEmpty(password)) {
            edtPwd.setText(password);
            edtPwd.setSelection(password.length());
        }
    }

    @OnClick({R.id.tv_remember_pwd, R.id.tv_forget_pwd, R.id.tv_login, R.id.tv_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_remember_pwd:
                rememberPwd = !rememberPwd;
                tvRememberPwd.setCompoundDrawablesWithIntrinsicBounds(
                        rememberPwd ? R.drawable.remember_pwd_selected : R.drawable.remember_pwd_unselected,
                        0, 0, 0);
                break;
            case R.id.tv_forget_pwd:
                jumpToActivity(ResetPwdActivity.class);
                break;
            case R.id.tv_login:
                login();
                break;
            case R.id.tv_register:
                jumpToActivity(RegisterActivity_V2.class);
                break;
        }
    }

    private void login() {
        userName = edtAccount.getText().toString();
        password = edtPwd.getText().toString();
        if (TextUtils.isEmpty(userName)) {
            showTopTips(R.string.hint_input_username);
            return;
        } else if (TextUtils.isEmpty(password)) {
            showTopTips(R.string.hint_input_password);
            return;
        }
        if (userName.trim().length() < 4) {
            showTopTips(R.string.account_length);
            return;
        }
        if (password.trim().length() < 4) {
            showTopTips(R.string.pwd_length);
            return;
        }

        String newPassword = MD5Util.string2MD5(password);
        Map<String, Object> params = new HashMap<>();
        params.put("user_name", userName);
        params.put("password", newPassword);
        //     params.put("logintype", 0 + "");
        presenter.userLogin(params);
    }

    @Override
    public void setPresenter(UserContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void loginSuccess(User user) {
        // 必须设置用户信息，建议在initSDK之前设置
        if (rememberPwd) {
            PreferenceUtils.putString(USERNAME, userName);
            PreferenceUtils.putString(PASSWORD, password);
        }
        Application.mZegoLiveRoom.setUser(user.getUser_code(), userName);
        Intent intent = new Intent();
        intent.setClass(LoginActivity_V2.this, AnchorStateActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void loginFailed(int code, String msg) {
        showTopTips(msg);
    }

    private void showSoftKeyboad() {
        /*FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) root.getLayoutParams();
        int topMargin = DeviceUtils.dp2px(this, 50);
        params.setMargins(0, -topMargin, 0, 0);
        root.setLayoutParams(params);*/
    }

    @Override
    public void showError(String message) {
        showTopTips(message);
    }
}
